<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <#if isManage==0>
        <title>流程代理授权</title>
    <#else>
        <title>代理配置管理</title>
    </#if>
    <#include "/pubHeadStyle.html">
</head>
<body>

<div class="bpmAuthorize" style="position: relative;height: 100%;">
    <div class="tablesize roles" style="position: absolute;top:0;right:0px;bottom: 0;left: 0px;padding:10px">
        <table id="agentSettingTab" lay-filter="agentSettingTab"></table>
    </div>
</div>
<div id="queryAgentDefModelList" class="bpmAuthorizeAdd " style="display: none;"></div>
<script type="text/html" id="headerToolsBar">
    <div class="layui-btn-container">
        <a class="layui-btn layui-btn-sm" lay-event="query">
            <i class="layui-icon layui-icon-search"></i>
            <span>查询</span>
        </a>
        <a class="layui-btn layui-btn-sm" lay-event="add">
            <i class="layui-icon layui-icon-add-1"></i>
            <span>新增</span>
        </a>
        <a class="layui-btn layui-btn-sm" lay-event="edit">
            <i class="layui-icon layui-icon-edit"></i>
            <span>编辑</span>
        </a>
        <a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="del">
            <i class="layui-icon layui-icon-delete"></i>
            <span>删除</span>
        </a>
        <a class="layui-btn layui-btn-sm" lay-event="reset">
            <i class="layui-icon layui-icon-refresh"></i>
            <span>重置</span>
        </a>
    </div>
    <form class="layui-form" action="" lay-filter="queryForm" style="margin-top:10px">
            <div class="table-top-filter">
        <#if isManage==1>
            <#--代理配置管理，特有查询条件-->
                <div class="table-filter-alone" style="float: left;">
                        <label class="layui-form-label">授权人</label>
                        <input type="hidden" name="Q_authId_L" class="layui-input">
                        <input type="text" name="Q_authName_SL" class="layui-input filter-value" placeholder="授权人">
                </div>
        </#if>
            <#--流程代理授权、代理配置管理，公共查询条件-->
                <div class="table-filter-alone">
                    <label class="layui-form-label">是否启用</label>
                    <select type="text" name="Q_enabled_N"  class="layui-input filter-value">
                        <option value="">全部</option>
                        <option value="0">禁止</option>
                        <option value="1">启用</option>
                    </select>
                </div>
                <div class="table-filter-alone">
                    <label class="layui-form-label">开始时间</label>
                    <input id="beginStartTime" type="text" name="Q_beginStartTime_DL" readonly="readonly" placeholder="开始时间" class="layui-input filter-value">
                </div>
                <div class="table-filter-alone">
                    <label class="layui-form-label">结束时间</label>
                    <input id="endEndTime" type="text" name="Q_endEndTime_DG" readonly="readonly" placeholder="结束时间" class="layui-input filter-value">
                </div>
            </div>
    </form>
</script>
<script type="text/html" lay-filter="bpmDefAuthorizeBar" id="bpmDefAuthorizeBar">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/html" id="switchTpl">
    <input type="checkbox" name="sex" value="{{d.id}}" lay-skin="switch" lay-text="启用|禁止" lay-filter="sexDemo" {{ d.enabled == 1 ? 'checked' : '' }}>
</script>

<script>
    layui.config({
        base: serverPath.systemPath + staticPath.systemPath //静态资源所在路径
    }).extend({
        index: 'index' //主入口模块
    }).use(['index','table','commons','layer','setter','common','totalFilter','admin','form','laydate'],function(){
        var table = layui.table;
        var commons = layui.commons;
        var layer = layui.layer;
        var setter = layui.setter;
        var common = layui.common;
        var totalFilter = layui.totalFilter;
        var admin = layui.admin;
        var form = layui.form;
        var $ = layui.$;
        var laydate = layui.laydate;

        var tableH = commons.tabHeight();

        //条件代理下，返回代理人
        function getMyAgent(conditionList) {
            var agentStr = '';
            for(var i=0;i<conditionList.length;i++){
                agentStr += conditionList[i].agent + ',';
            }
            return agentStr.substring(0,agentStr.length-1);
        }
        //时间转换
        function getMyDate(str) {
            var oDate = new Date(str),
                oYear = oDate.getFullYear(),
                oMonth = oDate.getMonth()+1,
                oDay = oDate.getDate(),
                // oHour = oDate.getHours(),
                // oMin = oDate.getMinutes(),
                // oSen = oDate.getSeconds(),
                oTime = oYear +'-'+ addZero(oMonth) +'-'+ addZero(oDay);
            return oTime;
        }
        //补零操作
        function addZero(num){
            if(parseInt(num) < 10){
                num = '0'+num;
            }
            return num;
        }

    /*-------------------------------↓列表数据渲染  begin↓---------------------------------------------------*/

        table.render({
            elem: '#agentSettingTab'
            , height: tableH
            , method: 'post'
            , toolbar: '#headerToolsBar'
            ,page: true //开启分页
    <#if isManage==0>
            , title: '流程代理授权列表'
            , url: serverPath.workflowPath + setter.workflowLinkPath + 'agentSetting/list'
            , cols: [[
                {type: 'checkbox'}
                , {field: 'id', title: 'id', align: 'center',hide:true}
                , {field: 'authName', title: '授权类型', align: 'center',templet: function(d){
                    if (d.authType==0){ return '全权代理'; }else if (d.authType==1) {   return '部分代理';  }else if (d.authType==2) {  return '条件代理'; }
                  }}
                , {field: 'startTime', title: '开始时间', align: 'center',templet:function (d) {
                    return  getMyDate(parseInt(d.startTime));
                  }}
                , {field: 'endTime', title: '结束时间', align: 'center',templet:function (d) {
                    return  getMyDate(parseInt(d.endTime));
                  }}
                , {field: 'agentDef', title: '流程名称', align: 'center',templet:function (d) {
                        if (d.authType==0){ return '全部流程';  }
                        else if (d.authType==1) {  return '<span onclick=onAuthFlowClick("'+d.id+'") style="color:#1E9FFF;" >部分流程</span>';  }
                        else if (d.authType==2) {  return '<a href="javascript:void(0);" onclick=onAuthActClick("'+ d.flowKey +'") class="layui-badge" style="margin-right: 5px;">'+d.flowName+'</a>';  }
                  }}
                , {field: 'enabled', title: '是否启用', align: 'center',templet: function(d){
                    if (d.enabled == 0){    return '<span style="color: red">禁用</span>' }else { return '<span style="color: green">启用</span>'   }
                  }}
                , {field: 'agent', title: '代理人', align: 'center',templet: function(d){
                    if(d.authType!=2){ return '<a href="#2">'+d.agent+'</a>' }else{ return getMyAgent(d.agentConditionList); }
                  }}
                ,{field: 'createTime', title: '创建时间', align: 'center',templet:function (d) {
                    if(d.createTime){   return  getMyDate(parseInt(d.createTime));  }
                    else if(d.updateTime){   return  getMyDate(parseInt(d.updateTime));  }
                    return "";
                    }}
                ,{field: 'Administration', title: '管理', align: 'center',toolbar: '#bpmDefAuthorizeBar'}
            ]],
    <#else>
            , title: '代理配置管理列表'
            , url: serverPath.workflowPath + setter.workflowLinkPath + 'agentSetting/manageList'
            , cols: [[
                {type: 'checkbox'}
                , {field: 'id', title: 'id', align: 'center',hide:true}
                , {field: 'authName', title: '授权人', align: 'center'}
                , {field: 'authName', title: '授权类型', align: 'center',templet: function(d){
                    if (d.authType==0){ return '全权代理';  }else if (d.authType==1) {  return '部分代理';  }else if (d.authType==2) {  return '条件代理';  }
                  }}
                , {field: 'startTime', title: '开始时间', align: 'center',templet:function (d) {
                    return  getMyDate(parseInt(d.startTime));
                  }}
                , {field: 'endTime', title: '结束时间', align: 'center',templet:function (d) {
                    return  getMyDate(parseInt(d.endTime));
                  }}
                , {field: 'agentDef', title: '流程名称', align: 'center',templet:function (d) {
                    if (d.authType==0){ return '全部流程';  }
                    else if (d.authType==1) {  return '<span onclick=onAuthFlowClick("'+d.id+'") style="color:#1E9FFF;" >部分流程</span>';  }
                    else if (d.authType==2) {  return '<a href="javascript:void(0);" onclick=onAuthActClick("'+ d.flowKey +'") class="layui-badge" style="margin-right: 5px;">'+d.flowName+'</a>';  }
                  }}
                , {field: 'agent', title: '代理人', align: 'center',templet: function(d){
                        if(d.authType!=2){ return '<a href="#2">'+d.agent+'</a>' }else{ return getMyAgent(d.agentConditionList); }
                  }}
                ,{field: 'createTime', title: '创建时间', align: 'center',templet:function (d) {
                    if(d.createTime){   return  getMyDate(parseInt(d.createTime)); }
                    else if(d.updateTime){   return  getMyDate(parseInt(d.updateTime));  }
                    return "";
                  }}
                ,{field:'enabled', title:'是否启用', align: 'center', templet: '#switchTpl', unresize: true}
                ,{field: 'Administration', title: '管理', align: 'center',toolbar: '#bpmDefAuthorizeBar'}
            ]],
    </#if>
            done:function () {
                //渲染时间控件
                table.resize('agentSettingTab');
                laydate.render({    elem: '#beginStartTime'   });
                laydate.render({    elem: '#endEndTime'     });
            }
        });
        totalFilter.init('agentSettingTab');
    /*-------------------------------↑列表数据渲染   end ↑---------------------------------------------------*/

        // 新增或修改弹窗
        function addOrUpdateHandle(type,data){
            layer.open({
                type: 2,
                title: type === 'add' ? '新增' : '修改',
                area: ['1100px', '630px'],
                content: serverPath.workflowPath + setter.workflowLinkPath +
                    <#if isManage==0>
                        'agentSetting/view/edit'
                    <#else>
                        'agentSetting/view/editAll'
                    </#if>
                    + (type === 'add' ?  '' : '?id='+data),
                skin: 'btn-class',
                btn: ['保存','取消'],
                btnAlign: 'c',
                yes: function(index,layero){
                    var form = layero.find('iframe').contents().find(".layui-form");
                    if (form.find("input[name=authtype]:checked").val()==0 <#if isManage!=0>&&form.find("input[name=authname]").val()</#if> &&form.find("#startTime").val()&&form.find("input[name=agent]").val()){
                            var flowkey = [];
                            var flowname = [];
                            $.each(form.find('#agentSettingTable tbody tr'),function (k,v) {
                                flowkey.push($(v).find('td').eq(0).find('span').attr('value'));
                                flowname.push($(v).find('td').eq(0).find('span').text());
                            });
                            var json = {};
                            json.authid = form.find("input[name=authid]").val();
                            json.authname = form.find("input[name=authname]").val();
                            json.id = form.find("input[name=id]").val();
                            json.startTime = form.find("#startTime").val().split(" 至 ")[0];
                            json.endTime = form.find("#startTime").val().split(" 至 ")[1] + " 23:59:59";
                            json.agentId = form.find("input[name=agentid]").val();
                            json.agent = form.find("input[name=agent]").val();
                            json.authType = form.find("input[name=authtype]:checked").val();
                            json.enabled = form.find("input[name=enabled]:checked").val();
                            json.agentDefList = [];
                            $.each(flowkey,function (k,v) {
                                json.agentDefList.push({
                                    flowkey:flowkey[k],
                                    flowname:flowname[k],
                                });
                            })
                            json.agentConditionList = [];
                    }else if (form.find("input[name=authtype]:checked").val() == 1 <#if isManage!=0>&&form.find("input[name=authname]").val()</#if> &&form.find("#startTime").val()&&form.find("input[name=agent]").val()&&form.find('#agentSettingTable tbody tr').length>0) {
                        var flowkey = [];
                        var flowname = [];
                        $.each(form.find('#agentSettingTable tbody tr'),function (k,v) {
                            flowkey.push($(v).find('td').eq(0).find('span').attr('value'));
                            flowname.push($(v).find('td').eq(0).find('span').text());
                        });
                        var json = {};
                        json.id = form.find("input[name=id]").val();
                        json.authid = form.find("input[name=authid]").val();
                        json.authname = form.find("input[name=authname]").val();
                        json.startTime = form.find("#startTime").val().split(" 至 ")[0];
                        json.endTime = form.find("#startTime").val().split(" 至 ")[1] + " 23:59:59";
                        json.agentid = form.find("input[name=agentid]").val();
                        json.agent = form.find("input[name=agent]").val();
                        json.authtype = form.find("input[name=authtype]:checked").val();
                        json.enabled = form.find("input[name=enabled]:checked").val();
                        json.agentDefList = [];
                        $.each(flowkey,function (k,v) {
                            json.agentDefList.push({
                                flowkey:flowkey[k],
                                flowname:flowname[k],
                            });
                        })
                        json.agentConditionList = [];
                    }else if (form.find("input[name=authtype]:checked").val() == 2 <#if isManage!=0>&&form.find("input[name=authname]").val()</#if> &&form.find("#startTime").val()&&form.find("input[name=flowname]").val()&&form.find("#agentCondition").val()) {
                        //代理条件设置
                        var agentConditionList = eval(form.find("#agentCondition").val());

                        //若代理人为空，则不进行保存
                        var isSave = true;
                        $.each(agentConditionList,function (k,v) {
                            //判断代理人ID是否为空
                            if(!v.agentid){
                                return isSave = false;
                            }
                        });

                        //是否保存
                        if(!isSave){
                            layer.msg("代理条件不能为空！",{icon:5,time:2500});
                            return false;
                        }else{
                            var flowkey = [];
                            var flowname = [];
                            $.each(form.find('#agentSettingTable tbody tr'),function (k,v) {
                                flowkey.push($(v).find('td').eq(0).find('span').attr('value'));
                                flowname.push($(v).find('td').eq(0).find('span').text());
                            });
                            var json = {};
                            json.id = form.find("input[name=id]").val();
                            json.authId = form.find("input[name=authid]").val();
                            json.authName = form.find("input[name=authname]").val();
                            json.startTime = form.find("#startTime").val().split(" 至 ")[0];
                            json.endTime = form.find("#startTime").val().split(" 至 ")[1] + " 23:59:59";
                            json.agentId = form.find("input[name=agentid]").val();
                            json.agent = form.find("input[name=agent]").val();
                            json.authType = form.find("input[name=authtype]:checked").val();
                            json.flowKey = form.find("input[name=flowkey]").attr('value');
                            json.flowName = form.find("input[name=flowname]").val();
                            json.enabled = form.find("input[name=enabled]:checked").val();
                            json.agentDefList = [];
                            json.agentConditionList = agentConditionList;
                        }
                    }else {
                        parent.layer.msg('请填写完整信息！',{time: 2500, icon:0});
                        return false;
                    }
                    $.ajax({
                        type: 'POST',
                        url: serverPath.workflowPath + setter.workflowLinkPath + 'agentSetting/save',
                        data: {
                            agentType:form.find("input[name=agentType]").val(),
                            json:JSON.stringify(json),
                        },
                        dataType:'json',
                        success: function(data){
                            if (data.code==0){
                                layer.close(index);
                                table.reload('agentSettingTab',{page: {curr: 1}})
                                layer.msg(data.msg,{time: 2500, icon:6});
                            }else {
                                layer.msg(data.msg,{time: 2500, icon:5});
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.alert("保存失败！" + XMLHttpRequest.status);
                        }
                    });
                    return false;
                },
                btn2: function(index,layero){
                    layer.close(index);
                },
            });
        }
        //监听性别操作
        form.on('switch(sexDemo)', function(obj){
            // layer.tips(this.value + ' ' + this.name + '：'+ obj.elem.checked, obj.othis);
            var status= '';
            if (obj.elem.checked==true){
                status=1;
            }else {
                status=0;
            }
            $.ajax({
                type: 'POST',
                url: serverPath.workflowPath + setter.workflowLinkPath + 'agentSetting/updStatus',
                data: {
                    id:this.value,
                    status:status,
                },
                dataType:'json',
                success: function(data){
                    if (data.code==0){
                        // table.reload('agentSettingTab',{page: {curr: 1}})
                        parent.layer.msg(data.msg,{time: 2500, icon:6});
                    }else {
                        parent.layer.msg(data.msg,{time: 2500, icon:5});
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    parent.layer.alert("保存失败！" + XMLHttpRequest.status);
                }
            });
        });
        //监听工具条
        table.on('tool(agentSettingTab)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

            if(layEvent === 'detail'){ //查看
                //do somehing
            } else if(layEvent === 'del'){ //删除
                layer.confirm('确认要删除该授权吗？', function(index){
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                    //向服务端发送删除指令
                    $.ajax({
                        url: serverPath.workflowPath + setter.workflowLinkPath + 'agentSetting/del',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            ids: data.id
                        },
                        success: function(data){
                            if(data.code !== 0){
                                layer.msg(data.msg, {time: 2500, icon:5});
                                return false;
                            }
                            layer.msg(data.msg, {time: 500, icon:6});
                            table.reload('agentSettingTab',{page: {curr: 1}});
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.alert("删除失败！" + XMLHttpRequest.status);
                        }
                    });
                });
            } else if(layEvent === 'edit'){ //编辑
                //do something
                addOrUpdateHandle('edit',data.id);
                //同步更新缓存对应的值
                // obj.update({
                //     username: '123'
                //     ,title: 'xxx'
                // });
            } else if(layEvent === 'LAYTABLE_TIPS'){
                layer.alert('Hi，头部工具栏扩展的右侧图标。');
            }
        });
        // 监听头工具栏事件
        table.on('toolbar(agentSettingTab)',function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data; //获取选中行数据
            switch (obj.event) {
                case 'query':
                    common.tableConditionRender("agentSettingTab","queryForm",{where:{}},false);
                    break;
                case 'add':
                    addOrUpdateHandle('add');
                    break;
                case 'edit':
                    if(data.length !== 1){
                        layer.msg("请选择一项数据!", {time: 2500, icon:5});
                        return false;
                    }
                    addOrUpdateHandle('edit',data[0].id);
                    break;
                case 'del':
                    if(data.length === 0){
                        layer.msg("请选择一项数据!", {time: 2500, icon:5});
                        return false;
                    }
                    var ids = $.map(data,function(v){
                        return v.id;
                    });
                    layer.confirm("确认删除吗?",{icon:0},function(index){
                        layer.close(index);
                        $.ajax({
                            url: serverPath.workflowPath + setter.workflowLinkPath + 'agentSetting/del',
                            type: 'post',
                            dataType: 'json',
                            data: {
                                ids: ids.toString()
                            },
                            success: function(data){
                                if(data.code !== 0){
                                    layer.msg(data.msg, {time: 2500, icon:5});
                                    return false;
                                }
                                layer.msg(data.msg, {time: 500, icon:6});
                                table.reload('agentSettingTab',{page: {curr: 1}});
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                layer.alert("删除失败！" + XMLHttpRequest.status);
                            }
                        });
                    });
                    break;
                case 'reset':
                    common.tableConditionRender("agentSettingTab","queryForm",{where:{}},true);
                    break;
            }
        });

        // 部分流程的点击触发弹窗
        window.onAuthFlowClick = function(defKey){
            $.ajax({
                url: serverPath.workflowPath + setter.workflowLinkPath + 'agentSetting/queryAgentDefModelList?id=' + defKey,
                type: 'get',
                dataType: 'json',
                success: function(data){
                    if(data.code !== 0){
                        layer.msg(data.msg, {time: 2500, icon:5});
                        return false;
                    }
                    $("#queryAgentDefModelList").html(' ');
                    $.each(data.data,function (k,v) {
                        $("#queryAgentDefModelList").append('<div class="layui-row">\n' +
                            '        <div class="layui-col-md4" style="text-align: center;background: #f2f2f2;line-height: 30px;">'+(k+1)+'</div>\n' +
                            '        <div class="layui-col-md8" style="text-align: center;line-height: 30px">'+v.flowName+'</div>\n' +
                            '    </div>')
                        $("#queryAgentDefModelList>div").eq(0).css('border-top','1px solid #ccc')
                    });
                    layer.open({
                        type: 1,
                        title: '流程详细信息',
                        area: ['360px', '330px'],
                        shadeClose: true,
                        content: $("#queryAgentDefModelList"),
                        success:function(layero){
                            // var mask = $(".layui-layer-shade");
                            // mask.appenTo(layero.parent());
                            //其中：layero是弹层的DOM对象
                            $(".layui-layer-shade").after(layero);
                        }

                    });
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert("获取流程信息失败！" + XMLHttpRequest.status);
                }
            });
        }

    // TODO弹窗大小待调整
        // 点击流程名称弹窗
        window.onAuthActClick = function(defKey){
            $.ajax({
                url: serverPath.workflowPath + setter.workflowLinkPath + 'actDefModel/getModelIdByDefKey?defKey=' + defKey,
                type: 'get',
                dataType: 'json',
                success: function(data){
                    if(data.code !== 0){
                        layer.msg(data.msg, {time: 2500, icon:5});
                        return false;
                    }
                    var url = serverPath.workflowPath + setter.workflowLinkPath + 'actDefModel/view/detail?modelId=' + data.data.id;
                    //Ajax获取
                    $.post(url, {}, function(str){
                        layer.open({
                            type: 1,
                            title: '流程详细信息',
                            area: ['600px', '400px'],
                            shadeClose: true,
                            content: str,
                            btn:['关闭'],
                            skin: 'btn-close'
                        });
                    });
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert("获取流程信息失败！" + XMLHttpRequest.status);
                }
            });
        }
    });
</script>
<style>
    .layui-table-tool-self {
        display: none;
    }
    .bpmAuthorize .table-top-filter div input {
        border-radius: 4px;
        float: left;
        width: 170px;
    }
    .bpmAuthorize .table-top-filter label.layui-form-label {
        width: 114px !important;
        float: left;
    }
    .bpmAuthorizeAdd .layui-row {
        border-bottom: 1px solid #ccc;
        border-left: 1px solid #ccc;
        border-right: 1px solid #ccc;
    }
</style>
</body>
</html>
<link rel="stylesheet" href="${ctx}/css/font/iconfontie.css" media="all"/>
<link rel="stylesheet" href="${ctx}/iconfont/iconfont.css"/>